<template>
  <div id="myLogin">
    <el-dialog title="登录" width="300px" center :visible.sync="useUserStore.isLogin">
      <el-form status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="name">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入账号" v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input prefix-icon="el-icon-view" type="password" placeholder="请输入密码"
            v-model="ruleForm.userPwd"></el-input>
          <a href="javascript:;" class="register" @click="toRegister" style="float:left">注册会员账号</a>
          <a href="javascript:;" class="register" @click="GetPassWord" style="float:right">忘记密码</a>
        </el-form-item>
        <el-form-item style="margin-top:-5px;">
          <el-button v-preventReClicks size="medium" type="primary" @click="login" style="width:100%; ">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus' // 第三方组件
import { userLogin } from '@/api/index'
import { useUserStore } from '@/stores/user'


// 第三方组件实例 (Element Plus)
const $message = ElMessage
const $modal = ElMessageBox

// Vue 生态相关
const userStore = useUserStore()
const router = useRouter()

// 状态定义 
const ruleForm = ref({
  userName: '',
  userPwd: '',
  errMsg: ''
})
const ruleFormRef = ref(null)



// 注册会员账号
const toRegister = () => {
  userStore.setIsLogin(false)
  router.push('/register')
}

//找回密码
const GetPassWord = () => {
  userStore.setIsLogin(false)
  router.push('/GetPassWord')
}

const login = async () => {
  if (!ruleForm.value.userName || !ruleForm.value.userPwd) {
    $message.error('账号或者密码不能为空!') // 第三方组件调用
    return false
  }

  try {
    const res = await userLogin({
      loginId: ruleForm.value.userName,
      password: ruleForm.value.userPwd,
      cusId: "",   
      webId: "", 
    })

    if (res.code === 2000) {
      $modal.msgSuccess('正在登陆中,正在跳转') // 第三方组件调用
      const data= userStore.setUser(res.data)
      userStore.setIsLogin(true)
      // 路由操作
      router.push('/index')
    } else {
      $message.error(res.message) // 第三方组件调用
    }
  } catch (error) {
    $message.error(error.message) // 第三方组件调用
  }
}

// 生命周期
onMounted(() => {
  emit('GetShoppingToCount')
})

// 自动暴露所有顶层绑定
defineExpose({
  ruleFormRef
})
</script>

<style>
.register:hover {
  color: #409EFF;
}
</style>